// https://www.lintcode.com/problem/insertion-sort-list/my-submissions

/**
 * Definition of singly-linked-list:
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *        this->val = val;
 *        this->next = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @return: The head of linked list.
     */
    ListNode * insertionSortList(ListNode * head) {
        if (!head) return NULL;
        ListNode * dummy = new ListNode(-1);
        while (head)
        {
            ListNode *t = dummy; //注意这个要放在里面！
            ListNode *next = head->next;
            while (t->next && t->next->val < head->val)
                t = t->next;
            head->next = t->next;
            t->next = head;
            head = next;
        }
        return dummy->next;
    }
};